package cn.tedu.csmall.passport.security;

import cn.tedu.csmall.commons.response.JsonResult;
import cn.tedu.csmall.commons.response.ServiceCode;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    // Token中的密钥
    private String secretKey = "jfdsfdslkjafdslkjafds";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 客户端在使用JWT时，应该将其添加在请求头中名为Authentication属性中，这是我们在设置的服务器端的约定，客户端必须遵守
        // 从请求头中获取名为Authentication的数据
        String jwt = request.getHeader("Authentication");
        log.debug("从请求头中获取Authentication：{}", jwt);
        // 判断是否获取到了数据
        if (!StringUtils.hasText(jwt)) {
            // 不存在有效的JWT数据，则直接放行
            // 因为某些请求本身也不要求登录，没有JWT数据是正常表现
            // 继续执行后续的过滤器链
            log.debug("没有获取到JWT数据，直接放行……");
            filterChain.doFilter(request, response);
            return; // 必须
        }

        // 如果代码可以执行到此处，表示从请求头中获取到了疑似有效的JWT
        log.debug("准备解析JWT数据……");
        String username = null;
        String permissionsString = null;
        try {
            JwtParser parser = Jwts.parser();
            Claims claims = parser.setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
            username = claims.get("username").toString();
            permissionsString = claims.get("permissions").toString();
            log.debug("从JWT中解析得到username：{}", username);
            log.debug("从JWT中解析得到permissions：{}", permissionsString);
        } catch (SignatureException e) {
            log.error("解析失败，JWT数据签名有误！");
            JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.FORBIDDEN, "JWT数据签名有误！");
            String jsonResultString = JSON.toJSONString(jsonResult);
            response.setContentType("application/json; charset=utf-8");
            response.getWriter().println(jsonResultString);
            return;
        } catch (MalformedJwtException e) {
            log.error("解析失败，JWT数据格式有误！");
            JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.FORBIDDEN, "JWT数据格式有误！");
            String jsonResultString = JSON.toJSONString(jsonResult);
            response.setContentType("application/json; charset=utf-8");
            response.getWriter().println(jsonResultString);
            return;
        } catch (ExpiredJwtException e) {
            log.error("解析失败，JWT数据已经过期！");
            JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.FORBIDDEN, "JWT数据已经过期！");
            String jsonResultString = JSON.toJSONString(jsonResult);
            response.setContentType("application/json; charset=utf-8");
            response.getWriter().println(jsonResultString);
            return;
        }

        // 将解析成功的JWT放回到Spring Security中
        List<SimpleGrantedAuthority> authorities
                = JSON.parseArray(permissionsString, SimpleGrantedAuthority.class);
        log.debug("将JSON格式的权限信息转换为集合：{}", authorities);
        Authentication authentication
                = new UsernamePasswordAuthenticationToken(username, null, authorities);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        log.debug("成功将JWT中的信息存入到Spring Security上下文，后续Spring Security将可以自动处理这些数据");
        // 放行，继续执行后续的过滤器链
        filterChain.doFilter(request, response);
    }

}
